﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using Epam.PeopleModel;
using PeopleListTask.Validators;

namespace PeopleListTask.CustomDataBinders
{
    public class PeopleEntityDataBinder:DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string name;
            DateTime date;
            double weight, height;
            bool frststep = FirstStepValidation(out name, out date, out weight, out height,controllerContext,bindingContext);
            var entity = new PeopleEntity(Guid.NewGuid(), name, date, weight, height);
            if(frststep)
            {
               PeopleValidators.ValidateName(entity,bindingContext);
               PeopleValidators.ValidateDate(entity, bindingContext);
               PeopleValidators.ValidateHeight(entity, bindingContext);
               PeopleValidators.ValidateWeight(entity, bindingContext);
            }
            return entity;
        }

        protected bool FirstStepValidation(out string name, out DateTime date, out double weight, out double height, ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var firststep = true;
            name = controllerContext.HttpContext.Request["Name"];
            if (!DateTime.TryParse(controllerContext.HttpContext.Request["BirthDate"], out date))
            {
                bindingContext.ModelState.AddModelError("BirthDate", "Invalid date");
                firststep = false;
            }
            if (!Double.TryParse(controllerContext.HttpContext.Request["weight"], out weight))
            {
                bindingContext.ModelState.AddModelError("weight", "Invalid weight");
                firststep = false;
            }
            if (!Double.TryParse(controllerContext.HttpContext.Request["height"], out height))
            {
                bindingContext.ModelState.AddModelError("height", "Invalid height");
                firststep = false;
            }
            return firststep;
        }

       
    }

}